<script setup lang="tsx">
import { reactive, ref, watch, onMounted, unref } from 'vue'
import { Form, FormSchema } from '@/components/Form'
import { useI18n } from '@/hooks/web/useI18n'
import { ElCheckbox } from 'element-plus'
import { useForm } from '@/hooks/web/useForm'
import { loginApi, getTestRoleApi, getAdminRoleApi, ckUdnApi } from '@/api/login'
import { useAppStore } from '@/store/modules/app'
import { usePermissionStore } from '@/store/modules/permission'
import { useRouter } from 'vue-router'
import type { RouteLocationNormalizedLoaded, RouteRecordRaw } from 'vue-router'
import { UserType } from '@/api/login/types'
import { useValidator } from '@/hooks/web/useValidator'
import { useUserStore } from '@/store/modules/user'
import { BaseButton } from '@/components/Button'
import SoftKey3W from '../components/Syunew3W.js'

const { required } = useValidator()

const emit = defineEmits(['to-register'])

const appStore = useAppStore()

const userStore = useUserStore()

const permissionStore = usePermissionStore()

const { currentRoute, addRoute, push } = useRouter()

const { t } = useI18n()

const rules = {
  username: [required()],
  password: [required()]
}

const schema = reactive<FormSchema[]>([
  {
    field: 'title',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return <h2 class="text-2xl font-bold text-center w-[100%]">{t('login.login')}</h2>
        }
      }
    }
  },
  {
    field: 'username',
    label: t('login.username'),
    // value: 'admin',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: '账号'
    }
  },
  {
    field: 'password',
    label: t('login.password'),
    // value: 'admin',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: '密码'
    }
  },
  {
    field: 'tool',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="flex justify-between items-center w-[100%]">
                <ElCheckbox v-model={remember.value} label={t('login.remember')} size="small" />
                {/* <ElLink type="primary" underline={false}>
                  {t('login.forgetPassword')}
                </ElLink> */}
              </div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'login',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="w-[100%]">
                <BaseButton
                  loading={loading.value}
                  type="primary"
                  class="w-[100%]"
                  onClick={signIn}
                >
                  {t('login.login')}
                </BaseButton>
              </div>
              {/* <div class="w-[100%] mt-15px">
                <BaseButton class="w-[100%]" onClick={toRegister}>
                  {t('login.register')}
                </BaseButton>
              </div> */}
            </>
          )
        }
      }
    }
  }
  // {
  //   field: 'other',
  //   component: 'Divider',
  //   label: t('login.otherLogin'),
  //   componentProps: {
  //     contentPosition: 'center'
  //   }
  // },
])

const remember = ref(userStore.getRememberMe)

const initLoginInfo = () => {
  const loginInfo = userStore.getLoginInfo
  if (loginInfo) {
    const { username, password } = loginInfo
    setValues({ username, password })
  }
}
onMounted(() => {
  initLoginInfo()
})

let UserName = '-',
  Password = '-',
  mSoftKey3A
const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose, setValues } = formMethods

const loading = ref(false)

const redirect = ref<string>('')

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)

const uLogin = async () => {
  var DevicePath
  mSoftKey3A = new SoftKey3W() //注意，由于USB的操作是异步的，所以所有函数的调用前必须加await !!!!!!!!!
  mSoftKey3A.Socket_UK.onmessage = function got_packet(Msg) {
    var PnpData = JSON.parse(Msg.data)
    if (PnpData.type == 'PnpEvent') {
      //如果是插拨事件处理消息
      if (PnpData.IsIn) {
        alert('UKEY已被插入，被插入的锁的路径是：' + PnpData.DevicePath)
      } else {
        userStore.reset()
        alert('UKEY已被拨出，被拨出的锁的路径是：' + PnpData.DevicePath)
      }
    }
  }
  DevicePath = await mSoftKey3A.FindPort(1) //'查找是否存在多把加密锁
  if (mSoftKey3A.GetLastError() == 0) {
    window.alert('系统上发现有2把及以上的加密锁，请只插入要进行的加密锁。')
    return false
  }
  DevicePath = await mSoftKey3A.FindPort(0) //'查找是否存在加密锁
  if (mSoftKey3A.GetLastError() != 0) {
    window.alert('未发现加密锁，请插入加密锁')
    return false
  }

  mSoftKey3A = new SoftKey3W()
  var DevicePath
  DevicePath = await mSoftKey3A.FindPort(1) //'查找是否存在多把加密锁
  if (mSoftKey3A.GetLastError() == 0) {
    window.alert('系统上发现有2把及以上的加密锁，请只插入要进行的加密锁。')
    return false
  }
  DevicePath = await mSoftKey3A.FindPort(0) //'查找是否存在加密锁
  if (mSoftKey3A.GetLastError() != 0) {
    window.alert('未发现加密锁，请插入加密锁')
    return false
  }

  var nlen
  var nlen1
  var addr = 100 //要读取的地址
  let lasterror = 0

  //先从地址0读到以前写入的字符串的长度
  var buf = await mSoftKey3A.YReadEx(addr, 1, 'ffffffff', 'ffffffff', DevicePath)
  var buf1 = await mSoftKey3A.YReadEx(addr + 1 + buf[0] + 1, 1, 'ffffffff', 'ffffffff', DevicePath)
  lasterror = await mSoftKey3A.GetLastError()

  nlen = buf[0]
  nlen1 = buf1[0]
  if (lasterror != 0) {
    window.alert('读取字符串长度错误。错误码：')
    return false
  }
  //再读取相应长度的字符串
  UserName = await mSoftKey3A.YReadString(addr + 1, nlen, 'ffffffff', 'ffffffff', DevicePath)
  Password = await mSoftKey3A.YReadString(
    addr + 1 + buf[0] + 1 + 1,
    nlen1,
    'ffffffff',
    'ffffffff',
    DevicePath
  )

  lasterror = await mSoftKey3A.GetLastError()
  if (lasterror != 0) {
    window.alert('读取字符串错误。错误码：')
    return false
  }
}

// 登录
const signIn = async () => {
  const formRef = await getElFormExpose()
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      const formData = await getFormData<UserType>()
      const res = await ckUdnApi({
        account: formData.username
      })
      if (res.data == '1') {
        await uLogin()
        if (UserName == '-') return
      }
      loading.value = true
      try {
        const res = await loginApi({
          account: formData.username,
          passwd: formData.password,
          uKey: UserName,
          uPass: Password
        })
        if (res) {
          // 是否记住我
          if (unref(remember)) {
            userStore.setLoginInfo({
              username: formData.username,
              password: formData.password
            })
          } else {
            userStore.setLoginInfo(undefined)
          }
          userStore.setRememberMe(unref(remember))
          userStore.setUserInfo({
            username: formData.username,
            password: formData.password,
            role: res.data.role,
            roleId: res.data.roleId,
            pluginToken: res.data.pluginToken,
            userId: res.data.userId,
            accountName: res.data.accountName
          })
          localStorage.setItem('role', res.data.role)
          userStore.setToken(res.data.token || '')

          // 是否使用动态路由
          if (appStore.getDynamicRouter) {
            getRole()
          } else {
            await permissionStore.generateRoutes('static', []).catch(() => {})
            permissionStore.getAddRouters.forEach((route) => {
              addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
            })
            permissionStore.setIsAddRouters(true)
            push({ path: redirect.value || permissionStore.addRouters[0].path })
          }
        }
      } finally {
        loading.value = false
      }
    }
  })
}

// 获取角色信息
const getRole = async () => {
  const formData = await getFormData<UserType>()
  const params = {
    roleName: formData.username
  }
  const res =
    appStore.getDynamicRouter && appStore.getServerDynamicRouter
      ? await getAdminRoleApi(params)
      : await getTestRoleApi(params)
  if (res) {
    const routers = res.data || []
    userStore.setRoleRouters(routers)
    appStore.getDynamicRouter && appStore.getServerDynamicRouter
      ? await permissionStore.generateRoutes('server', routers).catch(() => {})
      : await permissionStore.generateRoutes('frontEnd', routers).catch(() => {})

    permissionStore.getAddRouters.forEach((route) => {
      addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
    })
    permissionStore.setIsAddRouters(true)
    push({ path: redirect.value || permissionStore.addRouters[0].path })
  }
}

const OnYWriteStringWithLenBnt = async () => {
  var InString = 'test'
  var PwdString = 'dddd'

  var addr = 100 //要写入的地址
  mSoftKey3A = new SoftKey3W()
  var buf = new Uint8Array(1)
  var buf1 = new Uint8Array(1)
  var DevicePath
  DevicePath = await mSoftKey3A.FindPort(1) //'查找是否存在多把加密锁
  if (mSoftKey3A.GetLastError() == 0) {
    window.alert('系统上发现有2把及以上的加密锁，请只插入要进行的加密锁。')
    return false
  }
  DevicePath = await mSoftKey3A.FindPort(0) //'查找是否存在加密锁
  if (mSoftKey3A.GetLastError() != 0) {
    window.alert('未发现加密锁，请插入加密锁')
    return false
  }

  let lasterror = 0
  //写入字符串到地址101
  let OutLen = await mSoftKey3A.YWriteString(InString, addr + 1, 'ffffffff', 'ffffffff', DevicePath)
  buf[0] = OutLen
  //写入字符串的长度到地址100
  lasterror = await mSoftKey3A.YWriteEx(buf, addr, 1, 'ffffffff', 'ffffffff', DevicePath)

  //写入密码字符串到地址101
  let OutLen1 = await mSoftKey3A.YWriteString(
    PwdString,
    addr + 1 + InString.length + 1 + 1,
    'ffffffff',
    'ffffffff',
    DevicePath
  )
  buf1[0] = OutLen1
  //写入字符串的长度到地址100
  lasterror = await mSoftKey3A.YWriteEx(
    buf1,
    addr + 1 + InString.length + 1,
    1,
    'ffffffff',
    'ffffffff',
    DevicePath
  )

  if (lasterror != 0) window.alert('写入字符串长度错误。错误码：')
  else window.alert('写入字符串成功')
}

const OnYReadStringWithLenBnt = async () => {
  mSoftKey3A = new SoftKey3W()
  var DevicePath
  DevicePath = await mSoftKey3A.FindPort(1) //'查找是否存在多把加密锁
  if (mSoftKey3A.GetLastError() == 0) {
    window.alert('系统上发现有2把及以上的加密锁，请只插入要进行的加密锁。')
    return false
  }
  DevicePath = await mSoftKey3A.FindPort(0) //'查找是否存在加密锁
  if (mSoftKey3A.GetLastError() != 0) {
    window.alert('未发现加密锁，请插入加密锁')
    return false
  }

  var nlen
  var nlen1
  var addr = 100 //要读取的地址
  let lasterror = 0

  //先从地址0读到以前写入的字符串的长度
  var buf = await mSoftKey3A.YReadEx(addr, 1, 'ffffffff', 'ffffffff', DevicePath)
  var buf1 = await mSoftKey3A.YReadEx(addr + 1 + buf[0] + 1, 1, 'ffffffff', 'ffffffff', DevicePath)
  lasterror = await mSoftKey3A.GetLastError()

  nlen = buf[0]
  nlen1 = buf1[0]
  if (lasterror != 0) {
    window.alert('读取字符串长度错误。错误码：')
    return
  }
  //再读取相应长度的字符串
  var outstring = await mSoftKey3A.YReadString(addr + 1, nlen, 'ffffffff', 'ffffffff', DevicePath)
  var pwdstring = await mSoftKey3A.YReadString(
    addr + 1 + buf[0] + 1 + 1,
    nlen1,
    'ffffffff',
    'ffffffff',
    DevicePath
  )

  lasterror = await mSoftKey3A.GetLastError()
  if (lasterror != 0) {
    window.alert('读取字符串错误。错误码：')
  } else {
    window.alert('已成功读取字符串：' + outstring + ';' + pwdstring)
  }
}
</script>

<template>
  <!-- <button @click="OnYWriteStringWithLenBnt"> 写字符串(带长度) </button>
  <button @click="OnYReadStringWithLenBnt"> 读字符串(带长度) </button> -->
  <Form
    :schema="schema"
    :rules="rules"
    label-position="top"
    hide-required-asterisk
    size="large"
    class="dark:(border-1 border-[var(--el-border-color)] border-solid)"
    @register="formRegister"
  />
</template>
